# -*- coding: utf-8 -*-
import random
import string

import requests
from django.contrib.auth.models import User
from rest_framework import views, status
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from django.db import transaction
from myapp.models import WeChatAccount
from utils.constants import get_wechat_login_code_url


class WeChatLoginView(views.APIView):
    permission_classes = []

    @transaction.atomic
    def post(self, request):
        code = request.data.get('code', None)
        if not code:
            return Response({"code": "This field is required!"}, status=status.HTTP_400_BAD_REQUEST)
        url = get_wechat_login_code_url(code)
        resp = requests.get(url)

        openid = None
        session_key = None
        if resp.status_code != 200:
            return Response({"error": "WeChat server error."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        else:
            json = resp.json()
            if "errcode" in json:
                return Response({"error": json["errmsg"]})
            else:
                openid = json['openid']
                session_key = json['session_key']

            if not session_key:
                return Response({"error": "WeChat server doesn't return session key"})
            if not openid:
                return Response({"error": "WeChat server doesn't return openid"})

            user = User.objects.filter(username=openid).first()
            if not user:
                user = User()
                user.username = openid
                password = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10))
                user.set_password(password)
                user.save()
            wechataccount, _ = WeChatAccount.objects.get_or_create(user=user)
            if _:
                wechataccount.session_key = session_key
                wechataccount.openId = openid
                wechataccount.save()

            token, created = Token.objects.get_or_create(user=user)

            return Response({
                'token': token.key,
                'user_id': user.id
            })